/**
 * 
 */
package com.cipe.cmrs.controllers;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cipe.cmrs.bean.LinkRoleEntryBean;
import com.cipe.cmrs.bean.RestrictedUiElementBean;
import com.cipe.cmrs.bean.RestrictedUiElementRoleEntryBean;
import com.cipe.cmrs.bean.RoleManagementBean;
import com.cipe.cmrs.model.Role;
import com.cipe.cmrs.service.LinkService;
import com.cipe.cmrs.service.RestrictedUiElementsService;
import com.cipe.cmrs.service.RoleService;
import com.cipe.cmrs.util.LinkBeanCollectionEditor;
import com.cipe.cmrs.util.RestrictedUiElementBeanCollectionEditor;
 
/**
 * @author Incepio
 *
 */
@Controller
public class RoleManagementController extends BaseController {

	/**
	 * 
	 */
	private static final long	serialVersionUID	= -3823562098119817733L;
	@Autowired
	private RoleService			roleService;
	
	@Autowired
    private LinkService linkService;
	
    @Autowired
    RestrictedUiElementsService restrictedUiElementsService;	

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		super.initBinder(binder);
		binder.registerCustomEditor(List.class, "linkRoleEntryList", new LinkBeanCollectionEditor(List.class));
		binder.registerCustomEditor(List.class, "uiElementRoleEntryList", new RestrictedUiElementBeanCollectionEditor(List.class));		
	}	

	@RequestMapping("/secure/saveRoleManagement.do")
	public String saveRole(@ModelAttribute("rmb") RoleManagementBean rmb, BindingResult result, Model model, HttpServletRequest request) {
	
		String actionType = request.getParameter(getText("roleManagementLinkSave"));

		if (StringUtils.hasText(actionType)) {
			saveLinkRoles(rmb, result, model, request); 
		}else{
			saveUiElementRoles(rmb, result, model, request);
		}
		
		return "roleManagementList";
	}
	
	public void saveLinkRoles(RoleManagementBean rmb, BindingResult result, Model model, HttpServletRequest request) {
		try {
			List<LinkRoleEntryBean> linkBeanList = rmb.getLinkRoleEntryList();
			Map<Integer, List<Integer>> linkRoles = new HashMap<Integer, List<Integer>>();
			for (LinkRoleEntryBean linkBean : linkBeanList) {
				Integer linkId = linkBean.getLinkId();
				Integer roleId = linkBean.getId();
				if(!linkRoles.containsKey(linkId)){			
					List<Integer> roleIds = new ArrayList<Integer>();
					roleIds.add(roleId);
					linkRoles.put(linkId, roleIds);
				}else{					
					linkRoles.get(linkId).add(linkBean.getId());
				}
			}
		
			linkService.saveLinkRoles(linkRoles, getUserId(request)); 
			saveMessage(request, getText("editCountry.message.success"));
		
			setModelData(model);
			
		} catch (Exception e) {
			logger.error(getText("error.transaction"), e);
			saveError(request, getText("error.transaction"));
		}		
	}
	
	public void saveUiElementRoles(RoleManagementBean rmb, BindingResult result, Model model, HttpServletRequest request) {
		try {
			List<RestrictedUiElementRoleEntryBean> uiElementBeanList = rmb.getUiElementRoleEntryList();
			Map<Integer, List<Integer>> uiElementRoles = new HashMap<Integer, List<Integer>>();
			for (RestrictedUiElementRoleEntryBean uiElementRoleEntryBean : uiElementBeanList) {
				Integer uiElementId = uiElementRoleEntryBean.getUiElementId();
				Integer roleId = uiElementRoleEntryBean.getRoleId();
				if(!uiElementRoles.containsKey(uiElementId)){			
					List<Integer> roleIds = new ArrayList<Integer>();
					roleIds.add(roleId);
					uiElementRoles.put(uiElementId, roleIds);
				}else{					
					uiElementRoles.get(uiElementId).add(uiElementRoleEntryBean.getRoleId());
				}
			}			
//			restrictedUiElementsService.saveUiElementsRoles(uiElementBeanList);
			restrictedUiElementsService.saveUiElementsRoles(uiElementRoles);
 
			saveMessage(request, getText("editCountry.message.success"));
		
			setModelData(model);
			
		} catch (Exception e) {
			logger.error(getText("error.transaction"), e);
			saveError(request, getText("error.transaction"));
		}		
	}
	
	/*
	@RequestMapping("/secure/showAddRole.do")
	public String showAddRole(Model model) {
		model.addAttribute("role", new Role());
		return "editRole";
	}

	@RequestMapping("/secure/showEditRole.do")
	public String showEditRole(@RequestParam Integer id, Model model) {
		model.addAttribute("role", roleService.findById(id));
		return "editRole";
	}*/

	@RequestMapping("/secure/roleManagement.do")
	public String showRoleManagementList(Model model) {
		setModelData(model);		
		return "roleManagementList";
	}
	
	private void setModelData(Model model){
		List<Role> allRoles = roleService.findAll();
		model.addAttribute("roles", allRoles);
		RoleManagementBean rmb = new RoleManagementBean();
		
		// set data for link role management.
		Map<String, List> linkDataMap = linkService.getRoleManagementData();
		rmb.setLinkList(linkDataMap.get("linkBeanList"));
		rmb.setLinkRoleEntryList(linkDataMap.get("checkedRoleList"));
		
		// set data for uielement role management.		
//		Map<String, List> uiElelemtDataMap = restrictedUiElementsService.getRoleManagementData();
		Map<String, List> uiElelemtDataMap = restrictedUiElementsService.getRoleManagementData();	
		List<RestrictedUiElementBean> uiElementBeanList = uiElelemtDataMap.get("uiElementBeanList");
		Collections.sort(uiElementBeanList, new RestrictedUiElementBeanComparator());
		rmb.setUiElementList(uiElementBeanList);
		rmb.setUiElementRoleEntryList(uiElelemtDataMap.get("checkedRoleList"));
	
//		Map<String, Map<String, String>> allowedUiElementsMap = restrictedUiElementsService.getAllUiElements();		
//		rmb.setAllowedUiElementsMap(allowedUiElementsMap);
		
		model.addAttribute("rmb", rmb);		
	}
}

class RestrictedUiElementBeanComparator implements Comparator<RestrictedUiElementBean> {
	@Override
	public int compare(RestrictedUiElementBean arg0, RestrictedUiElementBean arg1) {
		return arg0.getSubmenuOrForm().compareTo(arg1.getSubmenuOrForm());
	}	
}